package com.study.webapp.jdk8;

import java.util.PriorityQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: study
 *
 * @description:
 *
 * @author: heqiang
 *
 * @create: 2020-05-06 16:12
 **/
public class ConditionTest2 {


    private int size = 10;
    private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(size);
    private Lock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();


    public static void main(String[] args) throws Exception {
        ConditionTest2 test2 = new ConditionTest2();
        Producer producer = test2.new Producer();
        Consumer consumer = test2.new Consumer();
        producer.start();
        consumer.start();
        Thread.sleep(0);
        producer.interrupt();
        consumer.interrupt();
    }


    class Consumer extends Thread {
        @Override
        public void run() {
            consumer();
        }

        volatile boolean flag = true;
        private void consumer() {
            while (flag) {
                lock.lock();
                try {
                    while (queue.size() == 0) {
                        try {
                            System.out.println("队列为空，等待数据");
                            notEmpty.await();
                        } catch (InterruptedException e) {
                            flag =false;
                        }
                    }
                    //取走第一个元素
                    queue.poll();
                    notFull.signal();
                    System.out.println("从队列取走一个元素，队列剩余"+queue.size()+"个元素");
                } finally {
                    lock.unlock();
                }
            }
        }
    }


    class Producer extends Thread {
        @Override
        public void run() {
            producer();
        }

        volatile boolean flag = true;
        private void producer() {
            while (flag) {
                lock.lock();
                try {
                    while (queue.size() == size) {
                        try {
                            System.out.println("队列已满，等待有空余时间");
                            notFull.await();
                        } catch (InterruptedException e) {
                            flag =false;
                        }
                    }
                    //插入一个元素
                    queue.offer(1);
                    notEmpty.signal();
                    System.out.println("向队列插入一个元素，队列剩余"+(size - queue.size())+"个元素");
                } finally {
                    lock.unlock();
                }
            }
        }
    }

}
